package com.example.project.controller;

import com.example.project.config.WebSecurityConfig;
import com.example.project.model.bo.UserBo;
import com.example.project.service.UserExtBusinessService;
import com.example.project.util.AssertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 控制器 博客出处：http://www.cnblogs.com/GoodHelper/
 *
 */
@Controller
public class UsersController {

    @Autowired
    private UserExtBusinessService userExtBusinessService;

    @GetMapping("/login")
    public String login() {
        return "admin/signin";
    }

    @PostMapping("/loginPost")
    public @ResponseBody Map<String, Object> loginPost(String account, String password, HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        UserBo userBo = userExtBusinessService.loadUsersInfo(account,password);
        if (!AssertUtils.isNotNull(userBo)) {
            map.put("errorcode", "error");
            map.put("message", "密码错误");
            return map;
        }
        // 设置session
        session.setAttribute(WebSecurityConfig.SESSION_KEY, account);
        map.put("errorcode", "success");
        map.put("message", "登录成功");
        return map;
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        // 移除session
        session.removeAttribute(WebSecurityConfig.SESSION_KEY);
        return "redirect:/login";
    }

}